package com.dz51.core.basedao.base.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

import com.dz51.core.basedao.base.IAbstractBaseDao;
import com.dz51.core.log4j.ILog4jManager;

/**
 * @Title: AbstractBaseDaoImpl.java
 * @Package com.dz51.core.basedao.impl
 * @Description: 基础dao层实现
 * @author Zhaoqt  
 * @date 2014-5-4 上午5:13:48
 * @version V1.0
 */
public abstract class AbstractBaseDaoImpl<E> 
				extends HibernateTemplate implements IAbstractBaseDao<E> {
	
	@Autowired
	protected ILog4jManager log4jManager;
	
	protected Class<? extends E> entityClass;
	
	@Autowired
	public void setSF(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}
	
	/**
	 * @Title: getHibernateSession
	 * @Description: <p>获取session 
	 * 				 <p>{@link org.springframework.orm.hibernate3.HibernateTemplate#getSession()}}
	 * @return
	 * @throws Exception    
	 * @return Session
	 */
	public Session getHibernateSession() throws Exception {
		return super.getSession();
	}
	
	
	/**
	 * @Title: getJDBCConnection
	 * @Description: <p>获取 JDBCConnection
	 * 				 <p>{@link org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)}
	 * @throws Exception    
	 * @return Connection
	 */
	public Connection getJDBCConnection() throws Exception {
		return DataSourceUtils.getConnection(SessionFactoryUtils.getDataSource(getSessionFactory()));
	}
	
	/**
	 * @Title: releaseJDBCConnection
	 * @Description: 关闭jdbc connection
	 * @param resultSet
	 * @param statement
	 * @param connection
	 * @throws Exception    
	 * @return void
	 */
	public void releaseJDBCConnection(ResultSet resultSet, Statement statement,
			Connection connection) throws Exception {
		if(resultSet != null) {
			resultSet.close();
			resultSet = null;
		} else {
			this.log4jManager.errorCustomLog(getClass().getName(), "releaseJDBCConnection", "ResultSet为空或已经关闭");
		}
		if(statement != null) {
			statement.close();
			statement = null;
			this.log4jManager.errorCustomLog(getClass().getName(), "releaseJDBCConnection", "Statement为空或已经关闭");
		}
		if(connection != null) {
			connection.close();
			connection = null;
			this.log4jManager.errorCustomLog(getClass().getName(), "releaseJDBCConnection", "Statement为空或已经关闭");
		}
	}

	public Class<? extends E> getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(Class<? extends E> entityClass) {
		this.entityClass = entityClass;
	}
	
}
